/*
 * 文件名: TreeNode.js
 * 作者: 破浪前行·吴
 * 创建日期: 2024/5/10
 * 描述: 树形节点类
 */
const { v4 } = require("uuid");
class TreeNode {
  #id; // 标识

  #name; // 名称

  #children; // 子节点

  #parent; // 父节点

  constructor() {
    this.#id = v4();
    this.#name = null;
    this.#children = [];
    this.#parent = null;
  }

  get id() {
    return this.#id;
  }

  /**
   * @param {string} value
   */
  set id(value) {
    this.#id = value;
  }

  get name() {
    return this.#name;
  }

  /**
   * @param {string} value
   */
  set name(value) {
    this.#name = value;
  }

  get children() {
    return this.#children;
  }

  get parent() {
    return this.#parent;
  }

  /**
   * @param {TreeNode} value
   */
  set parent(value) {
    this.#parent = value;
  }

  /**
   * @description 添加子节点
   * @param {TreeNode[]} node
   */
  addChildNode(...node) {
    node.forEach((item) => {
      item.parent = this;
    });
    this.#children.push(...node);
  }

  // 获取父，祖父...
  getChainParent() {
    const list = [];
    const loop = (node) => {
      const parent = node.parent;
      if (parent !== null) {
        list.push(parent);
        loop(parent);
      }
    };
    const parent = this.parent;
    parent !== null && loop(this);
    return list;
  }

  // 序列化
  serialize() {
    const loop = (list) => {
      return list.map((item) => {
        const newVal = {
          id: item.id,
          name: item.name,
          children: [],
        };
        if (item.children && item.children.length) {
          newVal.children = loop(item.#children);
        }
        return newVal;
      });
    };
    const serializeList = loop(this.children || []);
    return JSON.stringify(serializeList);
  }
}

module.exports = TreeNode;
